﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Helper;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using System.Security.Claims;

namespace DFGK_WMS.WebAPI.Controllers.基础数据
{
    /// <summary>
    /// 仓位管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TCellController : ControllerBase
    {
        private readonly ILogRepository logRepository;
        private readonly IConfiguration configuration;

        public TCellController(ITCellRepository tCellRepository, 
            ILogRepository logRepository,
            IConfiguration configuration)
        {
            TCellRepository = tCellRepository;
            this.logRepository = logRepository;
            this.configuration = configuration;
        }

        public ITCellRepository TCellRepository { get; }
        /// <summary>
        /// 添加仓位
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddTcell(TCellDto obj)
        {
            if (string.IsNullOrEmpty(obj.Code))
            {
                return Ok(BaseResult.Result("400", "编码不能为空！"));
            }
            string message = "";
            ApiResult apiresult = new ApiResult();
            bool IsOK = TCellRepository.AddTcell(obj,out message);
            if (IsOK)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 4;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "创建了仓位" + obj.Name;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                apiresult.code = "200";
                apiresult.message = "添加成功!";
                apiresult.data = true;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "添加失败！"+message;
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 修改仓位
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateTcell(TCellDto obj)
        {
            if (obj.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            if (string.IsNullOrEmpty(obj.Code))
            {
                return Ok(BaseResult.Result("400", "必填项不能为空！"));
            }
            string message = "";
            ApiResult apiresult = new ApiResult();
            bool IsOK = TCellRepository.UpdateTcell(obj,out message);
            if (IsOK)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 6;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "修改了仓位" + obj.Name;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                apiresult.code = "200";
                apiresult.message = "修改成功！";
                apiresult.data = true;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "修改失败！"+message;
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 删除库区
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelTcell(int uid)
        {
            if (uid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            ApiResult apiresult = new ApiResult();
            bool IsOK = TCellRepository.DelTcell(uid);
            if (IsOK)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int rid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 5;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = rid;
                logg.Description = uname + "删除了仓位";
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                apiresult.code = "200";
                apiresult.message = "删除成功!";
                apiresult.data = true;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "删除失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 根据id获取信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTcellById(int id)
        {
            if (id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var res = TCellRepository.GetTcellById(id);
            ApiResult apiresult = new ApiResult();
            if (res != null)
            {
                apiresult.code = "200";
                apiresult.message = "获取成功!";
                apiresult.data = res;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "获取失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 获取库房(仓库)信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTwarehouseList()
        {
            var res = TCellRepository.GetTwarehouseList();
            ApiResult apiresult = new ApiResult();
            if (res != null)
            {
                apiresult.code = "200";
                apiresult.message = "获取成功!";
                apiresult.data = res;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "获取失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 获取库区信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAreaList()
        {
            var res = TCellRepository.GetAreaList();
            ApiResult apiresult = new ApiResult();
            if (res != null)
            {
                apiresult.code = "200";
                apiresult.message = "获取成功!";
                apiresult.data = res;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "获取失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }

        /// <summary>
        /// 仓位左侧树形显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMenuitemList()
        {
            var mlist = TCellRepository.GetMenuitem();

            if(mlist!=null)
            {
                return Ok(BaseResult.Result(mlist, "获取成功！"));
            }

            return Ok(BaseResult.Result(null, "获取失败！"));
        }

        /// <summary>
        /// 批量设置
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdateSetUp(Tcellll obj)
        {
            ApiResult apiresult = new ApiResult();
            bool IsOK = TCellRepository.UpdateSetUp(obj);
            if (IsOK)
            {
                apiresult.code = "200";
                apiresult.message = "修改成功!";
                apiresult.data = true;
                return Ok(apiresult);
            }
            apiresult.code = "500";
            apiresult.message = "修改失败!";
            apiresult.data = true;
            return Ok(apiresult);
        }
        /// <summary>
        /// 批量生成仓位
        /// </summary>
        /// <param name="cellCreateBodyDTO"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BatchCreateCell(CellCreateBodyDTO cellCreateBodyDTO)
        {
            if (cellCreateBodyDTO.WhId.GetValueOrDefault() <= 0 || cellCreateBodyDTO.AreaId.GetValueOrDefault() <= 0 || cellCreateBodyDTO.ShelfIds == null || cellCreateBodyDTO.ShelfIds.Count <= 0)
            {
                return Ok(BaseResult.Result(false,"未选择库房或库区或货架","500"));
            }
            if (cellCreateBodyDTO.MaxLayer <= 0)
            {
                return Ok(BaseResult.Result(false, "最大层数未设置", "500"));
            }
            if (cellCreateBodyDTO.MaxColumn <= 0)
            {
                return Ok(BaseResult.Result(false, "最大列数未设置", "500"));
            }
            string message = "";
            var isOk = TCellRepository.BatchCreateCell(cellCreateBodyDTO,out message);
            if (isOk)
            {
                return Ok(BaseResult.Result(true, "批量添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }

        /// <summary>
        /// 枚举业务类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmBusinessType()
        {
            var list = BaseEnum.GetCodeRulesList<EmBusinessType>();

            return Ok(list);
        }

        /// <summary>
        /// 枚举仓位状态
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmCellStatus()
        {
            var list = BaseEnum.GetCodeRulesList<EmCellStatus>();

            return Ok(list);
        }

        /// <summary>
        /// 枚举仓位类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmCellType()
        {
            var list = BaseEnum.GetCodeRulesList<EmCellType>();

            return Ok(list);
        }

        /// <summary>
        /// 枚举高度类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmHeightType()
        {
            var list = BaseEnum.GetCodeRulesList<EmHeightType>();

            return Ok(list);
        }

        /// <summary>
        /// 库房库区货架
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetWarAreaShellList()
        {
            var list = TCellRepository.GetWarAreaShellList();

            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", 0));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 列表显示
        /// </summary>
        /// <param name="logicalPartCode"></param>
        /// <param name="fullStatus"></param>
        /// <param name="status"></param>
        /// <param name="cname"></param>
        /// <param name="whid"></param>
        /// <param name="areid"></param>
        /// <param name="sheid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCellList(string? logicalPartCode="", int fullStatus=3, int status=8, string? cname="", int whid=0, int areid=0, int sheid=0, int pageIndex=1, int pageSize=10)
        {
            if(pageIndex<=0 || pageSize<=0)
            {
                BaseResult.Result("400", "分页条件有误！");
            }
            int totalCount;
            var list = TCellRepository.GetCellList(logicalPartCode, fullStatus, status, cname,whid,areid,sheid, pageIndex, pageSize, out totalCount);

            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 更新仓位
        /// </summary>
        /// <param name="storeLocationCode"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdCell()
        {
            string hnBaseUrl = configuration["HNBaseUrl"];
            var token = await HttpHelper.GetToken(hnBaseUrl);
            using var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", token);
            // 发送GET请求
            HttpResponseMessage response = await client.GetAsync(hnBaseUrl+"/railway/v1/pda/store/location/list");
            // 检查请求是否成功
            if (response.IsSuccessStatusCode)
            {
                var res = await response.Content.ReadAsStringAsync();
                var responseObject = JsonConvert.DeserializeObject<LocationListDTO>(res);

                if (responseObject is null)
                {
                    return Ok(BaseResult.Result(null, "查询失败", "500"));
                }
                
                var cellList = TCellRepository.GetAllCellList();
                var delRes = TCellRepository.DelCellList(cellList);
                if (!delRes)
                {
                    return Ok(BaseResult.Result(false, "更新失败", "500"));
                }
                List<TCell> cells = new List<TCell>();
                foreach (var item in responseObject.data)
                {
                    var cell = new TCell()
                    {
                        Code=item.storeLocationCode,
                        WhId=item.storeId,
                        CreateDate=DateTime.Now,
                        Erpcode=item.storeLocationId.ToString(),
                        Name=item.remark,
                        Status = 1
                    };
                    cells.Add(cell);
                }
                if (!TCellRepository.AddCellList(cells))
                {
                    return Ok(BaseResult.Result(false, "更新失败", "500"));
                }
                return Ok(BaseResult.Result(true, "更新成功", "200"));
            }
            else
            {
                return Ok(BaseResult.Result(false, "请求失败", "500"));
            }
        }
    }
}
